package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 手机端登录
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //首页登录方式有登录和游客
        //判断是否登录
        if (!StringUtils.isEmpty(loginDto.getPhone()) && !StringUtils.isEmpty(loginDto.getPassword())) {
            //有账号和密码,查询数据库中是否存在
            LambdaQueryWrapper<ApUser> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ApUser::getPhone, loginDto.getPhone());
            ApUser user = getOne(lqw);
            if (user != null) {
                //数据库中存在该user,判断密码是否正确.加salt
                String password = loginDto.getPassword();
                String salt = user.getSalt();
                //进行md5加密,与数据库比对
                String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));
                if (!pwd.equals(user.getPassword())) {
                    //密码不正确
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
                }
                //登录成功,返回结果
                //获取Token
                String token = AppJwtUtil.getToken(user.getId().longValue());
                Map<String, Object> map = new HashMap<>();
                user.setPassword("");
                user.setSalt("");
                map.put("user", user);
                map.put("token", token);
                return ResponseResult.okResult(map);
            } else {
                //用户不存在
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        } else {
            //游客登录
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }
}
